package com.moleq.mgnetwork;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import android.os.Handler;
import android.os.Message;

import com.moleq.mgnetwork.MultiCommunication.CommunicationCallback;

public class NetworkMonitor extends Thread {

	private int mCycleTime;

//	private Map<String, String> mOnlineMap;

	private Map<String, Boolean> mMonitoringIP;

	private ConnectHandler commBridge = null;
	
	private boolean isError = false;

	/*
	private CommunicationCallback mCommunicationCallback = new CommunicationCallback() {

		@Override
		public void ipAddressConnected(String ipAddress, boolean isOnline) {
			// TODO Auto-generated method stub

		}

		@Override
		public void register(String ipAddress) {
			if(mMonitoringIP!=null){
				mMonitoringIP.put(ipAddress, true);	
			}
			
			System.out.println("register ip " + ipAddress);
			showLogMessage("register ip " + ipAddress);
		}

		@Override
		public void unRegister(String ipAddress) {
			if(mMonitoringIP!=null){
				mMonitoringIP.put(ipAddress, false);	
			}
			
			System.out.println("unregister ip " + ipAddress);
			showLogMessage("unregister ip " + ipAddress);
		}

		@Override
		public void showLogMessage(String strMsg) {
			
			Message msg = new Message();
			msg.what = 1;
			msg.obj = strMsg;
			msgHandler.sendMessage(msg );
			System.out.println(strMsg);
			
		}

	};
	*/

//	private Handler msgHandler;

	public NetworkMonitor(Map<String, Boolean> ipAddressList, int cycleTime,ConnectHandler comm) {

	
		this.mMonitoringIP = ipAddressList;
		this.mCycleTime = cycleTime;
//		this.mOnlineMap = new HashMap<String, String>();
		this.commBridge = comm;
	}

	@Override
	public void run() {

		

		while (!isError) {
			try {
				Thread.sleep(mCycleTime * 1000);

				ipAddressScan();

			} catch (InterruptedException e) {
				System.out.println("对指定的文件路径进行监控时产生异常，异常信息为：" + e.getMessage());
				isError = true;
			}
		}

		// TODO Auto-generated method stub
		super.run();
	}

	private void ipAddressScan() {

		if (mMonitoringIP != null) {

			Set<String> set = mMonitoringIP.keySet();
			Iterator<String> iterator = set.iterator();
			while (iterator.hasNext()) {
				String ipAddress  = iterator.next().toString();
				System.out.println("NetworkMonitor.ipAddressScan()" + ipAddress);
				if(commBridge!=null)
				commBridge.pingIp(ipAddress);
				
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}

	}

	public void release() {
		 isError = true;
		
	}

}
